<template>
  <div class="app-container" v-loading="isLoading">
    <SearchForm
      :search-form-config="searchFormConfig"
      @reset-btn-click="handlerReset"
      @search-btn-click="handlerSearch"
      ref="searData"
    ></SearchForm>
    <MTable
      header="中文成绩数据"
      :height="tableHeight"
      v-model:pagination="pagination"
      :loading="loading.tableLoading"
      :data="tableData"
      :columns="TABLECOLUMN"
      @update:pagination="paginationChange"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <template #card-header>
        <div class="action">
          <el-button
            type="primary"
            icon="CopyDocument"
            @click.stop="allSelection"
            >批量选择</el-button
          >
          <el-button
            type="primary"
            icon="TakeawayBox"
            @click.stop="handleAdd(xhs)"
            >打印</el-button
          >
          <!-- <el-button
              type="primary"
              icon="TakeawayBox"
              @click.stop="handlePreview(xhs)"
              >测试预览多个</el-button
            > -->
        </div>
      </template>
      <template #action="{ row }">
        <el-button
          type="primary"
          icon="View"
          @click="handlePreview([row.xh])"
          link
          >预览</el-button
        >
        <el-button
          type="primary"
          icon="TakeawayBox"
          link
          @click="handleAdd([row.xh])"
          >打印</el-button
        >
      </template>
    </MTable>
  </div>
</template>

<script setup name="ScoreInquiry">
import MTable from '@/components/MTable/index.vue'
import SearchForm from '@/components/SearchForm/index.vue'
import Form from '@/components/Form/index.vue'
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getZwcjList,
  getKcsxList,
  getZwcjXsbList,
  getNjList,
  getZyList,
  getZyfxList,
  getBjList,
  exportZwcjPrint,
} from '@/api/score-inquiry/index'
//表格高度
const tableHeight = window.innerHeight - 470 + 'px'
//表格
const table = ref(null)
//弹窗
const dialog = ref(null)
//弹窗里面的表单
const BuFormRef = ref(null)
// 搜索参数
const searchQuery = ref({})
// 分页器
const pagination = ref({
  page: 1,
  size: 1000,
  total: 0,
  pageSizes: ['全部数据', 1000, 500, 200, 100, 50, 10],
})
// 表格数据
const tableData = ref([])
//表格loading
const loading = ref({
  tableLoading: false,
})
//院系的值
const yuanXi = ref('')
//专业的值
const zhuanYe = ref('')
// 年级的值
const njdm = ref('')
//专业方向
const zyfxh = ref('')
//不显示不及格
const kcsxdmsList = ref([])
// 不显示
const kcsxdmssList = ref([])
//学号
const xh = ref('')
//不参与
const notCalculateKcsxsList = ref([])

//打印的loading
const isLoading = ref(false)
//搜索配置
const searchFormConfig = computed(() => {
  return {
    formItems: [
      {
        field: 'njdm',
        label: '年级',
        type: 'select',
        placeholder: '请选择年级',
        rulesitemStyle: {
          // width:'300px',
          // margin: '0  0 0 90px' ,
        },
        options: [],
        onChange: (val) => {
          njdm.value = val
          let params = {
            xsh: yuanXi.value,
            zyh: zhuanYe.value,
            zyfxh: zyfxh.value,
            rxnj: val,
          }
          bjList(params)
          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'bm')
          }, 15)
        },
      },
      {
        field: 'xsm',
        type: 'select',
        label: '院系',
        placeholder: '请选择院系',
        options: [],
        rules: [{ required: true, message: '请选择院系', trigger: 'change' }],
        onChange: (val) => {
          searData.value.BuFormRef.ruleFormRef.clearValidate('xh')
          zyList(val)
          yuanXi.value = val
          let params = {
            xsh: val,
            zyh: zhuanYe.value,
            zyfxh: zyfxh.value,
            rxnj: njdm.value,
          }
          bjList(params)
          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'zym')
          }, 10)
          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'zyfxmc')
            searchFormConfig.value.formItems[3].options = []
          }, 12)
          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'bm')
            // searchFormConfig.value.formItems[4].options = [];
          }, 15)
        },
      },
      {
        field: 'zym',
        type: 'select',
        label: '专业',
        placeholder: '请选择专业',
        options: [],
        onChange: (val) => {
          zhuanYe.value = val
          zyfxList(yuanXi.value, val)
          let params = {
            xsh: yuanXi.value,
            zyh: zhuanYe.value,
            zyfxh: '',
            rxnj: njdm.value,
          }
          bjList(params)

          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'zyfxmc')
            searchFormConfig.value.formItems[4].options = []
          }, 12)
          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'bm')
          }, 15)
        },
      },

      {
        field: 'zyfxmc',
        type: 'select',
        label: '专业方向',
        placeholder: '请选择专业方向',
        options: [],
        onChange: (val) => {
          zyfxh.value = val
          let params = {
            xsh: yuanXi.value,
            zyh: zhuanYe.value,
            zyfxh: val,
            rxnj: njdm.value,
          }
          bjList(params)
          setTimeout(() => {
            searData.value.BuFormRef.valueChange('', 'bm')
          }, 15)
        },
      },
      {
        field: 'bm',
        type: 'select',
        label: '班级',
        placeholder: '请选择班级',
        options: [],
        onChange: (val) => {},
      },
      {
        field: 'xh',
        type: 'input',
        label: '学号',
        placeholder: '请输入学号',
        default: '',
        rules: [{ required: true, message: '请输入学号', trigger: 'change' }],
        onChange: (val) => {
          searData.value.BuFormRef.ruleFormRef.clearValidate('xsm')
          xh.value = val
        },
      },
      {
        field: 'xm',
        type: 'input',
        label: '姓名',
        placeholder: '请输入姓名',
        default: '',
      },
      {
        field: 'kcsxdms',
        type: 'select',
        label: '不显示不及格',
        rulesitemStyle: {
          width: '360px',
          margin: '0 0 0 20px',
        },
        multiple: true,
        placeholder: '请选择不显示不及格',
        options: [],
        onChange: (val) => {
          kcsxdmsList.value = val
        },
      },
      {
        field: 'kcsxdmss',
        type: 'select',
        label: '不显示课程属性',
        multiple: true,
        placeholder: '请选择不显示课程属性',
        options: [],
        rulesitemStyle: {
          // width:'360px',
          // margin: '0  0 0 90px' ,
        },
        // label-width: '80px',
        onChange: (val) => {
          kcsxdmssList.value = val
        },
      },
      {
        field: 'sfyxj',
        type: 'select',
        label: '是否取有学籍',
        placeholder: '请选择是否取有学籍',
        options: [
          {
            label: '是',
            value: '是',
          },
          {
            label: '否',
            value: '否',
          },
        ],
        rulesitemStyle: {
          // width:'360px',
          // margin: '0  0 0 90px' ,
        },
        // label-width: '80px',
        onChange: (val) => {
          // kcsxdmssList.value=val
        },
      },
      {
        field: 'notCalculateKcsxs',
        type: 'select',
        label: '不参与计算的课程属性',
        multiple: true,
        placeholder: '请选择不参与计算的课程属性',
        options: [],
        rulesitemStyle: {
          width: '390px',
        },
        labelWidth: '160px',

        onChange: (val) => {
          notCalculateKcsxsList.value = val
        },
      },
    ],
    labelWidth: '110',
    itemStyle: {
      padding: '0 10px',
      margin: '0 10px',
    },
    itemColLayout: {
      lg: 5,
    },
  }
})
// 表单的数据
const formItems = searchFormConfig?.formItems ?? []
let formDataInit = {}
formItems.map((item) => {
  formDataInit[item.field] = item.default || ''
})
const formData = ref(formDataInit)
//学号
const xhs = ref([])
//搜索查询条件
const searData = ref(null)
//初始化加载
onMounted(() => {
  // handleQuery();
  njList() //年级
  kcsxList() //课程属性
  zwcjXsbList() //院系
  // zyList();//专业
})
const fileList = ref([])
const paginationChange = (val, b) => {
  isNaN(val.size) ? (pagination.value.size = 10000) : val.size
  // val.size == NaN
  getTableData()
}
//点击了重置按钮
const handlerReset = () => {
  if (searchFormConfig.value && searchFormConfig.value.formItems) {
    // 给 options 赋新值
    searchFormConfig.value.formItems[2].options = []
    searchFormConfig.value.formItems[3].options = []
    searchFormConfig.value.formItems[4].options = []
    kcsxdmsList.value = []
    kcsxdmssList.value = []
    notCalculateKcsxsList.value = []
    yuanXi.value = ''
    zhuanYe.value = ''
    njdm.value = ''
    zyfxh.value = ''
    xh.value = ''
  }
  // getTableData();
}
//点击了搜索
const handlerSearch = (queryInfo) => {
  // searData.value.BuFormRef.validate()
  if (
    (xh.value == '' && yuanXi.value == '') ||
    Object.keys(queryInfo).length === 0
  ) {
    searData.value.BuFormRef.ruleFormRef.validateField(['xsm', 'xh'])
    ElMessage.warning('院系或学号条件必选其一')
    return
  }
  searchQuery.value = { ...queryInfo }
  console.log(searchQuery.value)
  getTableData()
}
//点击了预览
const handlePreview = async (row) => {
  let params = {
    xhs: row,
    cjType: '3',
    kcsxdms: kcsxdmsList.value,
    kcsxdmss: kcsxdmssList.value,
    notCalculateKcsxs: notCalculateKcsxsList.value,
  }
  isLoading.value = true
  let res = await exportZwcjPrint(params)
  isLoading.value = false
  const file = new Blob([res], { type: 'application/pdf' })
  if (file) {
    const fileURL = URL.createObjectURL(file) // 创建文件的URL
    window.open(fileURL)
  }
  fileList.value = []
}
//点击了打印
const handleAdd = async (row) => {
  if (row.length == 0) return
  let params = {
    xhs: row,
    cjType: '3',
    kcsxdms: kcsxdmsList.value,
    kcsxdmss: kcsxdmssList.value,
    notCalculateKcsxs: notCalculateKcsxsList.value,
  }
  isLoading.value = true
  let res = await exportZwcjPrint(params)
  isLoading.value = false
  const file = new Blob([res], { type: 'application/pdf' })
  if (file) {
    const fileURL = URL.createObjectURL(file) // 创建文件的URL
    let iframe = document.createElement('iframe')
    iframe.setAttribute('id', 'printPDF')
    iframe.setAttribute('name', 'printPDF') // 不可少
    iframe.style.frameborder = 'no'
    iframe.style.display = 'none'
    iframe.style.pageBreakBefore = 'always' // 打印保留分页
    iframe.src = fileURL
    document.body.appendChild(iframe)
    // setTimeout(() => {
    //   document.getElementById("printPDF").contentWindow.print();
    // }, 1000);
    iframe.onload = function () {
      // 在iframe中触发打印命令
      iframe.contentWindow.print()
    }
    // window.URL.revokeObjectURL(iframe.src);
  }
  fileList.value = []
}
//点击了批量选择
const allSelection = (selection) => {
  table.value.mtable.toggleAllSelection()
}
// 点击查询
const handleQuery = async () => {
  pagination.value.page = 1
  await getTableData()
}
//选择单个或者全选
const handleSelectionChange = (selection) => {
  let xh = selection.map((item) => {
    return item.xh
  })
  xhs.value = xh
}
// 请求表格数据
const getTableData = async () => {
  const dataValue = {
    ...searchQuery.value,
    cjType: '3',
    pageNum: pagination.value.page,
    pageSize: pagination.value.size,
  }
  loading.value.tableLoading = true
  const data = await getZwcjList(dataValue)
  tableData.value = data.rows
  pagination.value.total = data.total
  loading.value.tableLoading = false
}
//班级
const bjList = async (data) => {
  let res = await getBjList(data)
  if (
    searchFormConfig.value &&
    searchFormConfig.value.formItems &&
    searchFormConfig.value.formItems[4]
  ) {
    // 给 options 赋新值
    searchFormConfig.value.formItems[4].options = res.data
  }
}
//专业方向
const zyfxList = async (yuanxi, zhuanye) => {
  if (!zhuanye) return
  let res = getZyfxList(yuanxi, zhuanye)
  if (
    searchFormConfig.value &&
    searchFormConfig.value.formItems &&
    searchFormConfig.value.formItems[3]
  ) {
    console.log(formData)
    // 给 options 赋新值
    searchFormConfig.value.formItems[3].options = res.data
  }
}
//专业下拉
const zyList = async (val) => {
  if (!val) return
  let res = await getZyList(val)
  if (
    searchFormConfig.value &&
    searchFormConfig.value.formItems &&
    searchFormConfig.value.formItems[2]
  ) {
    // 给 options 赋新值
    searchFormConfig.value.formItems[2].options = res.data
  }
}
//获取年级下拉
const njList = async () => {
  let res = await getNjList()
  if (
    searchFormConfig.value &&
    searchFormConfig.value.formItems &&
    searchFormConfig.value.formItems[0]
  ) {
    searchFormConfig.value.formItems[0].options = res.data
  }
}
//获取院系接口
const zwcjXsbList = async () => {
  const res = await getZwcjXsbList()
  if (
    searchFormConfig.value &&
    searchFormConfig.value.formItems &&
    searchFormConfig.value.formItems[1]
  ) {
    // formData.value.zym=''
    //       formData.value.zyfxmc=''
    //       formData.value.bm=''
    // 给 options 赋新值
    searchFormConfig.value.formItems[1].options = res.data
  }
}
//获取课程属性接口
const kcsxList = async () => {
  const res = await getKcsxList()
  if (
    searchFormConfig.value &&
    searchFormConfig.value.formItems &&
    searchFormConfig.value.formItems[7]
  ) {
    // 给 options 赋新值
    searchFormConfig.value.formItems[7].options = res.data
    searchFormConfig.value.formItems[8].options = res.data
    searchFormConfig.value.formItems[10].options = res.data
  }
}
//表格数据
const TABLECOLUMN = [
  {
    label: '序号',
    type: 'selection',
    width: 70,
  },
  {
    label: '序号',
    type: 'index',
    width: 70,
  },
  {
    label: '班级',
    prop: 'bm',
  },

  {
    label: '学号',
    prop: 'xh',
  },
  {
    label: '姓名',
    prop: 'xm',
  },
  {
    label: '专业方向',
    prop: 'zyfxmc',
    width: 160,
  },
  {
    label: '专业',
    prop: 'zym',
    width: 230,
  },
  {
    label: '院系',
    prop: 'xsm',
  },
  {
    label: '年级',
    prop: 'njdm',
  },
  {
    label: '操作',
    prop: 'action',
    fixed: 'right',
    width: 250,
  },
]
</script>

<style scoped lang="scss">
.action {
  margin-bottom: 15px;
}
:deep(.el-select__tags) {
  width: 400px !important;
  max-width: 400px !important;
}
:deep(.el-tag .is-closable) {
  width: 25px;
  margin-left: 0px;
}
:deep(.el-tag.is-closable) {
  padding-right: 2px;
}
:deep(.el-tag__close) {
  margin-left: 0px;
}
</style>
